package com.jinke.uang.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.AppApplication;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.cache.Acache;
import com.jinke.uang.cache.AcacheKeys;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.MineModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.OrderItemData;
import com.jinke.uang.bean.UserInformationData;
import com.jinke.uang.ui.activity.personal.RepaymentActivity;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 个人中心的fragment有可能会查询认证状态
 */
public class BorrowInFragment extends BaseNewFragment<CommonPresenter,MineModule>{
    Unbinder unbinder;

    @BindView(R.id.tvId)
    TextView tvId;
    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.tvMoney)
    TextView tvMoney;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvGoPayment)
    TextView tvGoPayment;
    @BindView(R.id.tvOverdueDefer)
    TextView tvOverdueDefer;
    @BindView(R.id.tvOverduePayment)
    TextView tvOverduePayment;
    @BindView(R.id.linOverdue)
    LinearLayout linOverdue;

    @BindView(R.id.linYesData)
    LinearLayout linYesData;
    @BindView(R.id.linNoData)
    LinearLayout linNoData;
    @BindView(R.id.tvNoDataText)
    TextView tvNoDataText;

    @BindView(R.id.linError)
    LinearLayout linError;
    @BindView(R.id.tvError)
    TextView tvError;
    private OrderItemData mOrderItemData;
    private String orderBackReasonCode;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_borrow_in, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void initData() {
        mPresenter.getData(HttpConstant.ORDER_DATA,"14","0");
        mPresenter.getData(HttpConstant.ORDER_DATA,"15","1");
        mPresenter.getData(HttpConstant.ORDER_DATA,"16","7");
        mPresenter.getData(HttpConstant.ORDER_DATA,"17","6");
    }
    @Override
    public void onResume() {
        super.onResume();
        initData();
    }
    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected MineModule getModule() {
        return new MineModule();
    }

    @Override
    public void onFirstVisible(Bundle savedInstanceState) {
        super.onFirstVisible(savedInstanceState);

        tvGoPayment.setOnClickListener(viewclick);
        tvOverdueDefer.setOnClickListener(viewclick);
        tvOverduePayment.setOnClickListener(viewclick);
        tvOverdueDefer.setVisibility(View.GONE);
    }


    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.tvGoPayment:
                    repayment();
                    break;
                case R.id.tvOverdueDefer:
                    //展期
                    rollover();
                    break;
                case R.id.tvOverduePayment:
                    repayment();
                    break;
                case R.id.linError:
                    //点击修改的
                    UserAuthRouter.getInstance().backRouter(orderBackReasonCode);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 状态展示
     *
     * @param data
     */
    @SuppressLint("SetTextI18n")
    private void fillUI(OrderItemData data) {
        String moneyUnit = getResources().getString(R.string.money_unit);

        tvId.setText(getStringResource(R.string.borrow_detail_page_order_code) + " " + data
                .getOrderId());
        // 审批状态: 3 已放款,待还款 6 已逾期 7 已展期
        String status = "";
        switch (data.getStatus()) {
            case Constant.ORDER_STATUS_AUDITING:
                //1审核中
                status = getStringResource(R.string.repayment_type_auditing);
                tvTime.setVisibility(View.GONE);
                linOverdue.setVisibility(View.GONE);
                tvGoPayment.setVisibility(View.GONE);

                //查询是否有资料回退
                mPresenter.getData(HttpConstant.USER_INFO_BACK,null);
                break;
            case Constant.ORDER_STATUS_WAITLEND:
                //2待放款
                status = getStringResource(R.string.repayment_type_waitlend);
                tvTime.setVisibility(View.GONE);
                linOverdue.setVisibility(View.GONE);
                tvGoPayment.setVisibility(View.GONE);
                break;
            case Constant.ORDER_STATUS_LENDING:
                //3 已放款,待还款
                status = getStringResource(R.string.repayment_type_lending);
                tvTime.setVisibility(View.VISIBLE);
                linOverdue.setVisibility(View.GONE);
                tvGoPayment.setVisibility(View.VISIBLE);

                linError.setVisibility(View.GONE);
                break;
            case Constant.ORDER_STATUS_OVERDUE:
                //6 已逾期
                //是否显示展期
                mPresenter.getData(HttpConstant.OPEN_EXTENSION,null);
                status = getStringResource(R.string.repayment_type_overdue);
                tvTime.setVisibility(View.VISIBLE);
                linOverdue.setVisibility(View.VISIBLE);
                tvGoPayment.setVisibility(View.GONE);
                linError.setVisibility(View.GONE);
                break;
            case Constant.ORDER_STATUS_ROLLOVER:
                //7 已展期
                status = getStringResource(R.string.repayment_type_rollover);
                tvTime.setVisibility(View.VISIBLE);
                linOverdue.setVisibility(View.GONE);
                tvGoPayment.setVisibility(View.VISIBLE);
                linError.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        tvStatus.setText(status);
        tvMoney.setText(getStringResource(R.string.borrow_detail_page_loan_of_num) + ": " +
                moneyUnit + StringUtils.getDotMoneyStr(String.valueOf(data.getApprovedAmt())));
        tvTime.setText(getStringResource(R.string.borrow_detail_page_expiration_time) + ": " +
                data.getLastPayDate());
    }

    /**
     * 立即展期的按钮
     */
    public void rollover() {
        // 逾期展期需要单独处理
        if (mOrderItemData.getStatus() == Constant.ORDER_LIST_TYPE_OVERDUE) {
            mPresenter.getData(HttpConstant.CALCULATED_ROLL_OVER_DATA,null,mOrderItemData.getOrderId());
        } else {
            ARouter.getInstance().build(RouterMap.REPAYMENT_PAGE).withString(RepaymentActivity
                    .ORDER_ID, mOrderItemData.getOrderId()).withString(RepaymentActivity
                    .ORDER_MONEY_NUM, String.valueOf(mOrderItemData.getTotalFee())).withBoolean
                    (RepaymentActivity.ORDER_MONEY_IS_ROLLOVER, true).navigation();
        }
    }
    //立即还款
    public void repayment() {
        ARouter.getInstance().build(RouterMap.REPAYMENT_PAGE).withString(RepaymentActivity
                .ORDER_ID, mOrderItemData.getOrderId()).withString(RepaymentActivity
                .ORDER_MONEY_NUM, String.valueOf(mOrderItemData.getRepayAmt())).withBoolean
                (RepaymentActivity.ORDER_MONEY_IS_ROLLOVER, false).navigation();
    }

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        if(apiType== HttpConstant.CALCULATED_ROLL_OVER_DATA){  //展期计算数据
//            BaseResponse<CalculateMoneyData> response = (BaseResponse<CalculateMoneyData>) o;
            BaseResponse<String> response = (BaseResponse<String>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                    ARouter.getInstance().build(RouterMap.ROLLOVER_PAGE).withString(RepaymentActivity
                            .ORDER_ID,null).navigation();

//                    ARouter.getInstance().build(RouterMap.ROLLOVER_PAGE).withString(RepaymentActivity
//                            .ORDER_ID, response.getData().getOrderId()).withString(RepaymentActivity
//                            .ORDER_MONEY_NUM, String.valueOf(response.getData().getTotalFee()))
//                            .withBoolean(RepaymentActivity.ORDER_MONEY_IS_ROLLOVER, true).navigation();
            }else {
                ToastUtils.showShort(getActivity(),response.getMessage());
            }
        }

        else if(apiType==HttpConstant.USER_INFO_BACK){  //资料回退
            BaseResponse<UserInformationData> response = (BaseResponse<UserInformationData>) o;
            final UserInformationData data = response.getData();
            if (data.getIsInformationWrong() == Constant.USER_DATA_BACK) {
                if (!TextUtils.isEmpty(data.getAuthPageCode())) {
                    //有资料回退
                    linError.setVisibility(View.VISIBLE);
                    orderBackReasonCode = data.getAuthPageCode();
                    Acache.get(AppApplication.getContext()).put(AcacheKeys.BACK, data
                            .getUserUuid());
                    linError.setOnClickListener(viewclick);
                    switch (data.getAuthPageCode()) {
                        case "identity_code":
                            tvError.setText(R.string.auth_error_realname);
                            break;
                        case "company_code":
                            tvError.setText(R.string.auth_error_work);
                            break;
                        case "borrowing_needs_code":
                            tvError.setText(R.string.auth_error_Moneyneed);
                            break;
                        case "personage_info_code":
                            tvError.setText(R.string.auth_error_person);
                            break;
                        case "contacts_code":
                            tvError.setText(R.string.auth_error_contact);
                            break;
                        case "bank_info_code":
                            tvError.setText(R.string.auth_error_bank);
                            break;
                        case "additional_information_code":
                            tvError.setText(R.string.auth_error_other);
                            break;
                        default:
                            break;
                    }
                }else{
                    linError.setVisibility(View.GONE);
                }
            } else {
                linError.setVisibility(View.GONE);
                Acache.get(AppApplication.getContext()).put(AcacheKeys.BACK, "");
            }
        }

        else if(apiType==HttpConstant.ORDER_DATA){ //根据多个订单类型获取数据
            BaseResponse<ArrayList<OrderItemData>> response = (BaseResponse<ArrayList<OrderItemData>>) o;
            if(null==response.getData()||response.getData().size()==0){
                tvNoDataText.setText(R.string.nodata_borrowin);
                return;
            }
            if (listType.equals("14")) {
                    for (OrderItemData item : response.getData()) {
                        mOrderItemData = item;
                        break;
                    }
                if (null == mOrderItemData) {
                    linYesData.setVisibility(View.GONE);
                    linNoData.setVisibility(View.VISIBLE);
                    tvNoDataText.setText(R.string.nodata_borrowin);
                } else {
                    linYesData.setVisibility(View.VISIBLE);
                    linNoData.setVisibility(View.GONE);
                    fillUI(mOrderItemData);
                }
                return;
            } else {
                linYesData.setVisibility(View.GONE);
                linNoData.setVisibility(View.VISIBLE);
                tvNoDataText.setText(R.string.nodata_borrowin);
            }

            if (listType.equals("15")) {
                for (OrderItemData item : response.getData()) {
                    mOrderItemData = item;
                    break;
                }
                if (null == mOrderItemData) {
                    linYesData.setVisibility(View.GONE);
                    linNoData.setVisibility(View.VISIBLE);
                    tvNoDataText.setText(R.string.nodata_borrowin);
                } else {
                    linYesData.setVisibility(View.VISIBLE);
                    linNoData.setVisibility(View.GONE);
                    fillUI(mOrderItemData);

                }
                return;
            } else {
                linYesData.setVisibility(View.GONE);
                linNoData.setVisibility(View.VISIBLE);
                tvNoDataText.setText(R.string.nodata_borrowin);
            }

            if (listType.equals("16")) {
                for (OrderItemData item : response.getData()) {
                    mOrderItemData = item;
                    break;
                }
                if (null == mOrderItemData) {
                    linYesData.setVisibility(View.GONE);
                    linNoData.setVisibility(View.VISIBLE);
                    tvNoDataText.setText(R.string.nodata_borrowin);
                } else {
                    linYesData.setVisibility(View.VISIBLE);
                    linNoData.setVisibility(View.GONE);
                    fillUI(mOrderItemData);
                }
                return;
            } else {
                linYesData.setVisibility(View.GONE);
                linNoData.setVisibility(View.VISIBLE);
                tvNoDataText.setText(R.string.nodata_borrowin);
            }

            if (listType.equals("17")) {
                for (OrderItemData item : response.getData()) {
                    mOrderItemData = item;
                    break;
                }
                if (null == mOrderItemData) {
                    linYesData.setVisibility(View.GONE);
                    linNoData.setVisibility(View.VISIBLE);
                    tvNoDataText.setText(R.string.nodata_borrowin);
                } else {
                    linYesData.setVisibility(View.VISIBLE);
                    linNoData.setVisibility(View.GONE);
                    fillUI(mOrderItemData);
                }
                return;
            } else {
                linYesData.setVisibility(View.GONE);
                linNoData.setVisibility(View.VISIBLE);
                tvNoDataText.setText(R.string.nodata_borrowin);
            }
        }

        else if(apiType==HttpConstant.OPEN_EXTENSION){
            BaseResponse<String> response = (BaseResponse<String>) o;
            if(response.getStatus() == Constant.HTTP_OK){
                if(response.isRel()){
                    tvOverdueDefer.setVisibility(View.VISIBLE);
                }else {
                    tvOverdueDefer.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void showError(Throwable e) {

    }
}
